﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.ComponentModel;
using System.Windows.Threading;

namespace WhileAwayWpf
{
    /// <summary>
    /// Interaction logic for ScreenSaverWindow.xaml
    /// </summary>
    public partial class ScreenSaverWindow : Window
    {
        private UserInfo userInfo = new UserInfo();
        private Random r = new Random();
        private DispatcherTimer countdownClock;
        private string[] files;
        private Storyboard zoomStoryBoard;
        EventCountdownConverter conv = new EventCountdownConverter();
        private EventWaitHandle settingsEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "C4F-WhileAway-Settings");

        public ScreenSaverWindow()
        {
            InitializeComponent();
            
            userInfo.Load();
            this.DataContext = userInfo;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
			zoomStoryBoard = (Storyboard)this.Resources["PhotoEffectStoryboard"];

            // Every second update clock if set
            countdownClock = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Background, new EventHandler(countdownClock_Tick), this.Dispatcher);
            countdownClock.Start();

            // Every ten seconds rotate image if enabled
            if (userInfo.PhotosEnabled)
            {
                string myPictures = userInfo.PhotoLocation;

                System.Threading.ThreadPool.QueueUserWorkItem((object o) =>
                {
                    files = System.IO.Directory.GetFiles(myPictures, "*.jpg", System.IO.SearchOption.TopDirectoryOnly);
                    Dispatcher.BeginInvoke(new Action(delegate() { SetBackgroundImageRandom(); }));
                });
            }
        }

		private void PhotoEffectStoryboardCompleted(object sender, EventArgs e)
        {
            SetBackgroundImageRandom();
        }

        void countdownClock_Tick(object sender, EventArgs e)
        {
			userInfo.UpdateReturnTimeRemaining();
        }

        private void SetBackgroundImageRandom()
        {
            if (files == null || files.Length == 0) return;

            int idx = r.Next(files.Length);
            string filename = files[idx];

            SetBackgroundImage(filename);
        }

        private void SetBackgroundImage(string filename)
        {
            MyImage.Source = new BitmapImage(new Uri(filename));
            (MyImage.Source as BitmapImage).DownloadFailed += new EventHandler<ExceptionEventArgs>(ScreenSaverWindow_DownloadFailed);

			zoomStoryBoard.Begin(MyImage);
        }

        void ScreenSaverWindow_DownloadFailed(object sender, ExceptionEventArgs e)
        {
            // We'll move on then!
            SetBackgroundImageRandom();
        }

        private void buttonImBack_Click(object sender, RoutedEventArgs e)
        {
            // Reset time away for next run
            userInfo.ReturnTime = DateTime.MinValue;
            userInfo.Save();

            settingsEvent.Set();

            Application.Current.Shutdown();
        }
    }

}

